import React, { Component } from 'react';
import { Checkbox, Row } from 'antd';

import styled from 'styled-components'

import styles from './style.less';
import request from '@/utils/request';
import { OPS_URL } from '@/config/query';

const CheckboxGroup = Checkbox.Group;

export const FilterRow = styled(Row)`
  overflow-y: auto;
  width: 100%;
  padding-left: 20px;
  span {
    color: rgba(0, 0, 0, 0.85);
  }
`

interface P {
  filter?: Function
}

class Filter extends Component<P, any> {
  state = {
    checkedList: [],
    indeterminate: true,
    checkAll: true,
    plainOptions: [],
    plainList: []
  };

  async componentDidMount() {
    const ans = await request(`${OPS_URL}/dict/permission_none/name`, { key: 'device.kind' }) || {};
    const checkedList = [];
    const plainOptions = [];
    const plainList = [];
    for (let [key, value] of Object.entries(ans)) {
      checkedList.push(key);
      plainList.push(key);
      plainOptions.push({
        label: <>
          <img src={require(`../../assets/images/icon/device/${key}.png`)} style={{ display: 'inline-block', padding: '0 8px', width: '36px' }} alt="" />
          <span style={{ fontSize: '16px', verticalAlign: 'middle' }}> {value}</span>
        </>, value: key
      });
    }
    this.setState({
      checkedList,
      plainList,
      plainOptions
    })
  }

  onChange = (checkedList) => {
    const { plainOptions } = this.state;
    this.props.filter(checkedList);
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && (checkedList.length < plainOptions.length),
      checkAll: checkedList.length === plainOptions.length,
    });
  }

  onCheckAllChange = (e) => {
    const { plainList } = this.state;
    this.props.filter(e.target.checked ? plainList : []);
    this.setState({
      checkedList: e.target.checked ? plainList : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  }

  render() {
    const { plainOptions, checkedList } = this.state;

    return (
      <section style={{ paddingLeft: '20px', fontSize: '16px' }}>
        <Checkbox
          indeterminate={this.state.indeterminate}
          onChange={this.onCheckAllChange}
          checked={this.state.checkAll}
        >
          <>
          <img src={require(`../../assets/images/icon/device/all.png`)} style={{ display: 'inline-block', padding: '0 8px', width: '36px' }} alt="" />
          <span style={{ fontSize: '16px', verticalAlign: 'middle' }}> 全选</span>
        </>
        </Checkbox>
        <section className={styles.filter}>
          <FilterRow>
            <CheckboxGroup options={plainOptions} value={checkedList} onChange={this.onChange} />
          </FilterRow>
        </section>
      </section>
    );
  }
}

export default Filter;